const LabelService = require("../service/label.service");

// 验证标签是否存在的中间件
const verifyLabelExists = async (ctx, next) => {
	//   获取标签
	const { labels } = ctx.request.body;

	// 判断每一个标签是否存在
	const newLabels = [];
	for (let name of labels) {
		const labelResult = await LabelService.getLabelByName(name);
		const label = { name };
		if (labelResult) {
			// 如果存在就获取标签id
			label.id = labelResult.id;
		} else {
			// 如果不存在就创建新标签，并获取新标签id
			const result = await LabelService.create(name);
			label.id = result.insertId;
		}
		newLabels.push(label);
	}

	ctx.labels = newLabels;

	await next();
};

module.exports = {
	verifyLabelExists
};
